import tkinter as tk
from tkinter import ttk
import tkinter.messagebox as messagebox

class CustomerDialog(tk.simpledialog.Dialog):
    def __init__(self, parent, customer_id=None):
        self.customer_id=customer_id
        self.result = False
        super().__init__(parent, "添加客户" if not customer_id else "编辑客户")

    def body(self, master):
        """创建对话框内容"""
        ttk.Label(master, text="姓名:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.E)
        self.name_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.name_var, width=25).grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(master, text="身份证号:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.E)
        self.pid_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.pid_var, width=25).grid(row=1, column=1, padx=5, pady=5)

        ttk.Label(master, text="联系电话:").grid(row=2, column=0, padx=5, pady=5, sticky=tk.E)
        self.phone_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.phone_var, width=25).grid(row=2, column=1, padx=5, pady=5)

        ttk.Label(master, text="联系地址:").grid(row=3, column=0, padx=5, pady=5, sticky=tk.E)
        self.address_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.address_var, width=25).grid(row=3, column=1, padx=5, pady=5)

        # 如果是编辑模式，加载现有数据
        if self.customer_id:
            self.load_customer_data()

        return master

    def load_customer_data(self):
        try:
            cursor = self.master.db_connection.cursor()
            cursor.execute("SELECT * FROM userinfo WHERE customerID = %s", (self.customer_id,))
            result = cursor.fetchone()
            cursor.close()

            if result:
                self.name_var.set(result[1])
                self.pid_var.set(result[2])
                self.phone_var.set(result[3])
                self.address_var.set(result[4] if result[4] else "")
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载客户数据失败: {str(e)}")

    def apply(self):
        name = self.name_var.get()
        pid = self.pid_var.get()
        phone = self.phone_var.get()
        address = self.address_var.get()

        if not name or not pid or not phone:
            messagebox.showwarning("输入错误", "姓名、身份证号和联系电话不能为空！")
            return

        if len(pid) != 18 and (len(pid) != 17 or not pid[-1].isalnum()):
            messagebox.showwarning("输入错误", "身份证号格式不正确！")
            return

        if len(phone) != 11 or not phone.isdigit():
            messagebox.showwarning("输入错误", "联系电话必须为11位数字！")
            return
        try:
            cursor = self.master.db_connection.cursor()

            if self.customer_id:
                # 更新现有客户
                cursor.execute("""
                    UPDATE userinfo
                    SET customerName = %s,
                        PID          = %s,
                        telephone    = %s,
                        address      = %s
                    WHERE customerID = %s
                    """, (name, pid, phone, address, self.customer_id))
            else:
                # 添加新客户
                cursor.execute("""
                    INSERT INTO userinfo (customerName, PID, telephone, address)
                    VALUES (%s, %s, %s, %s)
                    """, (name, pid, phone, address))

            self.master.db_connection.commit()
            cursor.close()

            self.result = True
        except Exception as e:
            messagebox.showerror("数据库错误", f"保存客户信息失败: {str(e)}")


class CardDialog(tk.simpledialog.Dialog):
    def __init__(self, parent, card_id=None):
        self.card_id = card_id
        self.result = False
        super().__init__(parent, "添加银行卡" if not card_id else "编辑银行卡")

    def body(self, master):
        try:
            cursor = self.master.db_connection.cursor()
            cursor.execute("SELECT savingID, savingName FROM deposit")
            self.deposit_types = cursor.fetchall()
            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"获取存款类型失败: {str(e)}")
            self.deposit_types = []

        try:
            cursor = self.master.db_connection.cursor()
            cursor.execute("SELECT customerID, customerName FROM userinfo")
            self.customers = cursor.fetchall()
            cursor.close()
        except Exception as e:
            messagebox.showerror("数据库错误", f"获取客户列表失败: {str(e)}")
            self.customers = []

        ttk.Label(master, text="存款类型:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.E)
        self.saving_id_var = tk.StringVar()
        deposit_choices = [f"{deposit[0]}: {deposit[1]}" for deposit in self.deposit_types]
        self.deposit_combo = ttk.Combobox(master, textvariable=self.saving_id_var, values=deposit_choices,
                                          state="readonly")
        self.deposit_combo.grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(master, text="客户:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.E)
        self.customer_id_var = tk.StringVar()
        customer_choices = [f"{customer[0]}: {customer[1]}" for customer in self.customers]
        self.customer_combo = ttk.Combobox(master, textvariable=self.customer_id_var, values=customer_choices,
                                           state="readonly")
        self.customer_combo.grid(row=1, column=1, padx=5, pady=5)

        ttk.Label(master, text="开卡金额:").grid(row=2, column=0, padx=5, pady=5, sticky=tk.E)
        self.open_money_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.open_money_var, width=25).grid(row=2, column=1, padx=5, pady=5)

        ttk.Label(master, text="密码:").grid(row=3, column=0, padx=5, pady=5, sticky=tk.E)
        self.pass_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.pass_var, width=25, show="*").grid(row=3, column=1, padx=5, pady=5)

        if self.card_id:
            self.load_card_data()

        return master

    def load_card_data(self):
        try:
            cursor = self.master.db_connection.cursor()
            cursor.execute("SELECT * FROM cardinfo WHERE cardID = %s", (self.card_id,))
            result = cursor.fetchone()
            cursor.close()

            if result:
                for deposit in self.deposit_types:
                    if deposit[0] == result[2]:  # savingID
                        self.saving_id_var.set(f"{deposit[0]}: {deposit[1]}")
                        break
                # 设置客户
                for customer in self.customers:
                    if customer[0] == result[8]:  # customerID
                        self.customer_id_var.set(f"{customer[0]}: {customer[1]}")
                        break
                # 设置开卡金额
                self.open_money_var.set(str(result[4]))
                # 设置密码
                self.pass_var.set(result[6])
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载银行卡数据失败: {str(e)}")

    def apply(self):
        # 从存款类型选择中提取ID
        saving_id_str = self.saving_id_var.get().split(':')[0].strip()
        if not saving_id_str.isdigit():
            messagebox.showwarning("输入错误", "请选择存款类型！")
            return

        saving_id = int(saving_id_str)

        # 从客户选择中提取ID
        customer_id_str = self.customer_id_var.get().split(':')[0].strip()
        if not customer_id_str.isdigit():
            messagebox.showwarning("输入错误", "请选择客户！")
            return

        customer_id = int(customer_id_str)

        # 获取开卡金额
        open_money = self.open_money_var.get()
        if not open_money:
            messagebox.showwarning("输入错误", "请输入开卡金额！")
            return

        try:
            open_money = float(open_money)
            if open_money < 1.0:
                messagebox.showwarning("输入错误", "开卡金额不能小于1元！")
                return
        except ValueError:
            messagebox.showwarning("输入错误", "请输入有效的开卡金额！")
            return

        # 获取密码
        password = self.pass_var.get()
        if not password:
            messagebox.showwarning("输入错误", "请输入密码！")
            return

        if len(password) != 6 or not password.isdigit():
            messagebox.showwarning("输入错误", "密码必须为6位数字！")
            return

        try:
            cursor = self.master.db_connection.cursor()

            if self.card_id:
                # 更新银行卡信息
                cursor.execute("""
                    UPDATE cardinfo
                    SET savingID   = %s,
                        customerID = %s,
                        openMoney  = %s,
                        pass       = %s
                    WHERE cardID = %s
                    """, (saving_id, customer_id, open_money, password, self.card_id))
            else:
                # 生成新卡号
                cursor.execute("SELECT MAX(cardID) FROM cardinfo")
                max_card_id = cursor.fetchone()[0]
                if max_card_id:
                    new_card_id = str(int(max_card_id) + 1).zfill(16)
                else:
                    new_card_id = "1010357600000001"

                # 添加新银行卡
                cursor.execute("""
                    INSERT INTO cardinfo (cardID, savingID, customerID, openMoney, balance, pass,
                                         IsReportLoss, curID)
                    VALUES (%s, %s, %s, %s, %s, %s, '否', 'RMB')
                    """, (new_card_id, saving_id, customer_id, open_money, open_money, password))

            self.master.db_connection.commit()
            cursor.close()

            self.result = True
        except Exception as e:
            messagebox.showerror("数据库错误", f"保存银行卡信息失败: {str(e)}")


class DepositDialog(tk.simpledialog.Dialog):
    """存款类型对话框"""

    def __init__(self, parent, saving_id=None):
        self.saving_id = saving_id
        self.result = False
        super().__init__(parent, "添加存款类型" if not saving_id else "编辑存款类型")

    def body(self, master):
        """创建对话框内容"""
        ttk.Label(master, text="存款名称:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.E)
        self.name_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.name_var, width=25).grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(master, text="存款描述:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.E)
        self.desc_var = tk.StringVar()
        ttk.Entry(master, textvariable=self.desc_var, width=25).grid(row=1, column=1, padx=5, pady=5)

        # 如果是编辑模式，加载现有数据
        if self.saving_id:
            self.load_deposit_data()

        return master

    def load_deposit_data(self):
        """加载存款类型数据"""
        try:
            cursor = self.master.db_connection.cursor()
            cursor.execute("SELECT * FROM deposit WHERE savingID = %s", (self.saving_id,))
            result = cursor.fetchone()
            cursor.close()

            if result:
                self.name_var.set(result[1])
                self.desc_var.set(result[2] if result[2] else "")
        except Exception as e:
            messagebox.showerror("数据库错误", f"加载存款类型数据失败: {str(e)}")

    def apply(self):
        """保存存款类型信息"""
        name = self.name_var.get()
        desc = self.desc_var.get()

        if not name:
            messagebox.showwarning("输入错误", "存款名称不能为空！")
            return

        try:
            cursor = self.master.db_connection.cursor()

            if self.saving_id:
                # 更新现有存款类型
                cursor.execute("""
                    UPDATE deposit
                    SET savingName = %s,
                        descrip    = %s
                    WHERE savingID = %s
                    """, (name, desc, self.saving_id))
            else:
                # 添加新存款类型
                cursor.execute("""
                    INSERT INTO deposit (savingName, descrip)
                    VALUES (%s, %s)
                    """, (name, desc))

            self.master.db_connection.commit()
            cursor.close()

            self.result = True
        except Exception as e:
            messagebox.showerror("数据库错误", f"保存存款类型信息失败: {str(e)}")